<template>
  <div class="quota">
    <span>可用采购额度：</span>
    <span>{{ form.availableCredit }}</span>
    <c-button type="link" @click="applyQuota">申请更多额度</c-button>
    <c-modal
      v-model="quotaVisible"
      title="申请采购额度"
      width="400px"
      @ok="submit"
      @cancel="close"
    >
      <c-form
        v-model="form"
        ref="form"
        :rules="rules"
        :data="formData"
        :col="{ labelCol: { style: 'width: 100px;' } }"
      ></c-form>
    </c-modal>
  </div>
</template>

<script>
import { querySupplierQuotaByContract, purchaseCredit } from "@/api/quota";

export default {
  props: {
    data: {
      type: Object,
      default: () => {
        return {};
      }
    }
  },
  data() {
    return {
      quotaVisible: false,
      form: {
        ...this.data,
        availableCredit: undefined,
        usedCredit: undefined,
        creditAmount: undefined
      },
      formData: [
        {
          label: "申请对象",
          prop: "companyName",
          type: "text"
        },
        {
          label: "合约月",
          prop: "futuresContract",
          type: "text"
        },
        {
          label: "已用额度",
          prop: "usedCredit",
          type: "text"
        },
        {
          label: "可用额度",
          prop: "availableCredit",
          type: "text"
        },
        {
          label: "增加额度",
          prop: "creditAmount"
        }
      ],
      rules: {
        creditAmount: [{ required: true, message: "请输入增加额度" }]
      }
    };
  },
  methods: {
    //   弹窗关闭回调
    close() {
      this.form.creditAmount = undefined;
    },
    //   确认提交
    submit() {
      this.$refs.form.validated().then(() => {
        purchaseCredit({
          sellerCompanyId: this.data.companyId,
          futuresContractCode: this.data.futuresContract,
          requestCreditAmount: this.form.creditAmount,
          categoryId: this.data.categoryId,
          orderUserId: this.data.userId
        }).then(() => {
          this.$message.success("操作成功");
          this.quotaVisible = false;
        });
      });
    },
    // 查询可用额度
    queryUsableQuota() {
      querySupplierQuotaByContract({
        companyId: this.data.companyId,
        futuresContractCode: this.data.futuresContract,
        categoryId: this.data.categoryId
      }).then(res => {
        this.form.availableCredit = res ? res.availableCredit : 0;
        this.form.usedCredit = res ? res.usedCredit : 0;
      });
    },
    // 申请更多额度
    applyQuota() {
      this.quotaVisible = true;
      // this.queryUsableQuota()
    }
  },
  created() {
    this.queryUsableQuota();
  }
};
</script>
